import sys

import uiautomator2 as u2
from PyQt5.Qsci import QsciScintilla
from PyQt5.QtGui import QColor
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QFileDialog, \
    QDialog

from .editor import QScintillaCodeEditor, QScintillaLogEditor
from .scrcpy_view import ScrcpyGraphicsView
from .script import coder
from .utils.uidump import get_android_hierarchy, find_clickable_element


class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.btn_start_record = None
        self.editor = None
        self.log_output = None
        self.scrcpy_view = None
        self.coder = coder
        self.device = u2.connect()

        self.setWindowTitle("Autotest")
        self.setGeometry(100, 100, 1280, 800)

        # 创建主布局
        main_layout = QHBoxLayout(self)

        # 第一部分：竖向排列的按钮
        self.left_panel = self.create_left_panel()
        # 第二部分：代码编辑器 + 日志显示
        self.script_log_panel = self.create_script_log_panel()
        # 第三部分：scrcpy 手机投屏
        self.scrcpy_panel = self.create_scrcpy_panel()

        # 设置布局
        main_layout.addWidget(self.left_panel)
        main_layout.addWidget(self.script_log_panel)
        main_layout.addWidget(self.scrcpy_panel)

        self.setLayout(main_layout)

        # 设置背景色
        # palette = QPalette()
        # palette.setColor(QPalette.Background, Qt.grey)
        # palette.setBrush(QPalette.Background, QBrush(QColor(55, 55, 55)))
        # self.setPalette(palette)

    def create_left_panel(self):
        panel = QWidget(self)
        btn_layout = QVBoxLayout()

        # 创建几个按钮
        self.btn_start_record = QPushButton("开始录制")
        btn_stop_record = QPushButton("结束录制")
        btn_replay = QPushButton("回放")
        btn_delay = QPushButton("延迟1秒")
        btn_x = QPushButton("预留")

        btn_layout.addWidget(self.btn_start_record)
        btn_layout.addWidget(btn_stop_record)
        btn_layout.addWidget(btn_replay)
        btn_layout.addWidget(btn_delay)
        btn_layout.addWidget(btn_x)

        self.btn_start_record.clicked.connect(self.start_record)
        btn_stop_record.clicked.connect(self.stop_record)
        btn_replay.clicked.connect(self.run)
        btn_delay.clicked.connect(self.delay_one_second)

        panel.setLayout(btn_layout)
        panel.setMinimumWidth(100)

        return panel

    def create_script_log_panel(self):
        panel = QWidget(self)
        layout = QVBoxLayout()

        # 添加按钮：运行和清空代码
        btn_layout = QHBoxLayout()
        btn_run = QPushButton("Run")
        btn_clear = QPushButton("Clear")
        btn_import = QPushButton("Import Script")
        btn_export = QPushButton("Export Script")

        btn_layout.addWidget(btn_run)
        btn_layout.addWidget(btn_clear)
        btn_layout.addWidget(btn_import)
        btn_layout.addWidget(btn_export)

        # 连接按钮事件
        btn_run.clicked.connect(self.run)
        btn_clear.clicked.connect(self.clear)
        btn_export.clicked.connect(self.export_file)

        # 上部分：QScintilla 代码编辑器
        self.editor = QsciScintilla()
        QScintillaCodeEditor(self.editor).config()
        # 下部分：日志显示
        self.log_output = QsciScintilla()
        QScintillaLogEditor(self.log_output).config()

        self.editor.setText(self.coder.reset())

        # 添加到垂直布局
        layout.addLayout(btn_layout)
        layout.addWidget(self.editor, stretch=2)
        layout.addWidget(self.log_output, stretch=1)

        panel.setLayout(layout)

        return panel

    def create_scrcpy_panel(self):
        scrcpy_panel = QWidget(self)
        scrcpy_layout = QVBoxLayout()
        self.scrcpy_view = ScrcpyGraphicsView()  # 使用 QGraphicsView 显示 scrcpy 投屏界面
        # scrcpy_view = ScrcpyView()
        self.scrcpy_view.click_listener = self.on_click
        self.scrcpy_view.moved_listener = self.on_moved

        scrcpy_layout.addWidget(self.scrcpy_view)
        scrcpy_panel.setLayout(scrcpy_layout)
        scrcpy_panel.setMaximumWidth(380)
        scrcpy_panel.setMinimumWidth(300)
        return scrcpy_panel

    def on_click(self, x, y):
        # 生成脚本
        hierarchy_json = get_android_hierarchy(self.device)
        resource_id = find_clickable_element(x, y, hierarchy_json)
        if resource_id:
            print("click resource id:" + resource_id)
            self.editor.append(self.coder.click(resource_id))
            self.move_cursor_to_end()
        else:
            print('no resource id')

    def on_moved(self, dx, dy, x, y, duration):
        print(f"move {dx},{dy} to {x},{y} use {duration}s")
        self.editor.append(self.coder.swipe(dx, dy, x, y, duration))
        self.move_cursor_to_end()

    def start_record(self):
        if self.scrcpy_view.is_recording:
            return
        self.scrcpy_view.is_recording = True
        self.btn_start_record.setText('录制中')
        self.btn_start_record.setStyleSheet(f"QPushButton {{ background-color: {QColor(0, 200, 0).name()}; }}")
        # 弹出输入框，提示输入case的 feature,story
        self.open_case_info_dialog()

    def stop_record(self):
        self.scrcpy_view.is_recording = False
        self.btn_start_record.setText('开始录制')
        self.btn_start_record.setStyleSheet("")
        self.coder.stop()

    def delay_one_second(self):
        self.editor.insert(self.coder.sleep(1))

    def run(self):
        from .runscript import run_script
        run_script(self.editor.text(), self.log_output.append)

    def clear(self):
        """清空代码编辑器"""
        self.editor.setText(self.coder.reset())

    def move_cursor_to_end(self):
        # 获取文本行数和每行字符数，将光标移动到最后一个字符
        line_count = self.editor.lines()
        last_line_length = self.editor.lineLength(line_count - 1)  # 最后一行的长度
        self.editor.setCursorPosition(line_count - 1, last_line_length)  # 移动到最后一行最后一个字符

    def open_case_info_dialog(self):
        """
        弹框提示输入case的feature,story
        """
        from .dialog import InputCaseInfoDialog
        dialog = InputCaseInfoDialog()  # 创建对话框
        if dialog.exec_() == QDialog.Accepted:  # 如果点击了“确定”
            input_data = dialog.get_input_data()  # 获取输入数据
            print(f"输入的用例信息：{input_data}")
            self.editor.append(self.coder.allure_feature_story(input_data[0], input_data[1]))
            self.move_cursor_to_end()

    def export_file(self):
        # 弹出文件对话框，让用户选择保存路径和文件名
        filePath, _ = QFileDialog.getSaveFileName(self, '导出文件', 'untitled.py', 'All Files (*)')
        if filePath:
            # 用户选择了文件路径，将数据写入到这个文件中
            with open(filePath, 'w') as file:
                file.write(self.editor.text())
            print(f'文件已导出至：{filePath}')



def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
